package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.controller.LogicController;
import edu.ynu.se.xiecheng.achitectureclass.common.utils.ResultMap;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.LoginResponseDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.GHUser;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.service.UserService;
import edu.ynu.se.xiecheng.achitectureclass.util.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "大棚用户实体")
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends LogicController<UserService, UserDao, User, Long> {
    public UserController(@Autowired UserService userService) {
        super(userService);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResultMap getLogin(@RequestBody GHUser user) {
        System.out.println("接收到的用户信息：" + user);
        GHUser loginUser = (GHUser) getService().getUserByUsername(user.getUsername());
        if (loginUser == null) {
            return ResultMap.error("用户不存在！");
        }
        // 直接比较前端传来的已加密密码
        String inputPassword = user.getPassword();

         System.out.println("输入的密码：" + inputPassword);
         System.out.println("数据库中的密码：" + loginUser.getPassword());

        if (!loginUser.getPassword().equals(inputPassword)) {
            return ResultMap.error("密码错误！");
        }
        // 签发Token
        String token = JWTUtils.creatToken(loginUser.getUsername(), 1);
        System.out.println(token);
        System.out.println(loginUser.getUsername());
        System.out.println(loginUser.getRole());
        System.out.println(loginUser.getId());
        // 创建响应DTO
        LoginResponseDTO responseDTO = new LoginResponseDTO(
                token,
                loginUser.getUsername(),
                loginUser.getRole(),
                loginUser.getId()
        );
        return ResultMap.success(responseDTO);
    }

    //需要 admin 权限才能访问
    @ApiOperation("测试身份权限")
    @PostMapping("/testAdmin")
    @RequiresRoles(value = {"admin"})
    public ResultMap testAdmin(@RequestParam String username) {
        if (username != null) {
            return ResultMap.success("admin 授权成功！");
        } else {
            return ResultMap.error("admin 授权失败！");
        }
    }

    //不需要权限即可访问（弊端就是  没权限和没登陆都能访问，可以加个guest基本权限）
    @RequestMapping("/testGuest")
    public ResultMap testGuest(@RequestParam String username) {
        if (username != null) {
            return ResultMap.success("guest 授权成功！");
        } else {
            return ResultMap.error("guest 授权失败！");
        }
    }

}
